package com.sgj.gulimall.order.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.rabbitmq.client.Channel;
import com.sgj.gulimall.order.entity.OrderEntity;
import com.sgj.gulimall.order.entity.OrderReturnReasonEntity;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sgj.common.utils.PageUtils;
import com.sgj.common.utils.Query;

import com.sgj.gulimall.order.dao.OrderItemDao;
import com.sgj.gulimall.order.entity.OrderItemEntity;
import com.sgj.gulimall.order.service.OrderItemService;

// 监听的队列
@RabbitListener(queues = {"hello-java-queue"})
@Slf4j
@Service("orderItemService")
public class OrderItemServiceImpl extends ServiceImpl<OrderItemDao, OrderItemEntity> implements OrderItemService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<OrderItemEntity> page = this.page(
                new Query<OrderItemEntity>().getPage(params),
                new QueryWrapper<OrderItemEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 自动监听队列消息
     * @param message   RabbitMQ原生返回数据
     * @param entity    T<发送消息的类型>  Spring会自动匹配消息对应类型
     */
    @RabbitHandler      // 重载区分不同的消息
    public void recieveMessage(Message message, OrderReturnReasonEntity entity, Channel channel) {
        // 消息内容
        byte[] body = message.getBody();
        // 消息头
        MessageProperties properties = message.getMessageProperties();
        // 自增
        long deliveryTag = properties.getDeliveryTag();
        try {
            // 非批量签收
            if (deliveryTag % 2 == 0) {
                // 收货
                channel.basicAck(deliveryTag, false);
                log.info("[OrderItemServiceImpl][recieveMessage] 货物[{}]已签收", deliveryTag);
            } else {
                // 拒收 第三个参数若为false，则该消息直接丢弃，若为true，则发送回服务器，返回队列
                channel.basicNack(deliveryTag, false, false);
                log.info("[OrderItemServiceImpl][recieveMessage] 货物[{}]未签收", deliveryTag);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        log.info("[OrderItemServiceImpl][recieveMessage] entity:{}", JSONObject.toJSONString(entity));
    }

    @RabbitHandler
    public void recieveMessage2(OrderEntity entity) {
        log.info("[OrderItemServiceImpl][recieveMessage2] entity:{}", JSONObject.toJSONString(entity));
    }

}